#pragma once

#include <iostream>
#include <string>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

namespace Client
{
    enum
    {
        USAGE_ERROR = 1,
        SOCKET_ERROR
    };

    class udpClient
    {
    public:
        udpClient(const std::string &serverip, const uint16_t &serverport)
            : _serverport(serverport), _serverip(serverip), _sock(-1)
        {
        }

        void initClient()
        {
            // 1.
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sock < 0)
            {
                std::cerr << "_sock socket error" << std::endl;
                exit(SOCKET_ERROR);
            }
            std::cout << "_sock socket success" << std::endl;
        }

        void start()
        {
            // 1. 主线程发送
            struct sockaddr_in server;
            bzero(&server, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());

            std::string buffer;
            while (true)
            {
                std::cout << "Please Enter# ";
                std::getline(std::cin, buffer);

                sendto(_sock, buffer.c_str(), buffer.size(), 0, (struct sockaddr *)&server, sizeof(server));
            }

            // // 2. 可以创建子线程接收
            // char message[1024];
            // int n = recvfrom(_sock, message, sizeof(message) - 1, 0, (struct sockaddr *)&server, sizeof(server));
            // if (n > 0)
            //     message[n] = 0;
            // std::cout << "udpClient recvfrom: " << message << std::endl;
        }

        ~udpClient() {}

    private:
        int _sock;
        uint16_t _serverport;
        std::string _serverip;
    };
}